/*
 作    者：王曙光
 时    间：2011年9月20日
 功    能：人员列表基础控件(list)业务处理相关js
 */

var UserList = function() {
	var _ucstyle = 0;
	var _uccascade = 0;
	var _uctype = 0;
	var _ucicon = 0;
	var _ucunfoldcascade = 0;
	//封装图片和脚本路径，使得模块独立
	function GetRealResourcePath() {
		var url = document.location.href;
		var splitUrlCount = url.split("?")[0].split("/").length;
		var realPath = "";
		for(var i = 0; i < splitUrlCount - 5; i++) {
			realPath += "../";
		}
		return realPath + "UserWebControl.UserSelect/";
	}

	//构造部门JSON
	function Dept2JSON(dept) {
		var dstr = "";
		dstr += "{";
		dstr += "\"name\":" + "\"" + dept.deptName + "\",";
		dstr += "\"id\":" + "\"" + dept.deptId + "\",";
		dstr += "\"pid\":" + "\"" + dept.fatherId + "\",";
		dstr += "\"cnum\":" + dept.childNodes.length + ",";
		if(dept.deptName == "******") {
			dstr += "\"unum\":0";
		} else {
			dstr += "\"unum\":" + dept.childUsers.length + "";
		}
		dstr += "}"
		return dstr;
	}

	//构造用户JSON
	function User2JSON(user, pid) {
		var ustr = "";
		ustr += "{";
		ustr += "\"id\":" + "\"" + user.userId + "\",";
		ustr += "\"name\":" + "\"" + user.userName + "\",";
		ustr += "\"pid\":" + "\"" + pid + "\",";
		ustr += "\"color\":" + "\"" + user.color + "\",";
		ustr += "\"visiable\":true";
		ustr += "}";
		return ustr;
	}

	//递归子部门和用户
	function GetChildNode(dept, i, pid) {
		if(!UStore.usable()) {
			UStoreConst.hash["dept_" + pid + "_" + i.toString()] = Dept2JSON(dept);
		} else {
			UStore.set("dept_" + pid + "_" + i.toString(), Dept2JSON(dept));
		}
		if(dept.deptName != "******") {
			for(var j = 0; j < dept.childUsers.length; j++) {
				if(!UStore.usable()) {
					UStoreConst.hash["user_" + dept.deptId + "_" + j.toString()] = User2JSON(dept.childUsers[j], dept.deptId);
				} else {
					UStore.set("user_" + dept.deptId + "_" + j.toString(), User2JSON(dept.childUsers[j], dept.deptId));
				}
			}
		}
		for(var k = 0; k < dept.childNodes.length; k++) {
			GetChildNode(dept.childNodes[k], k, dept.deptId);
		}
	}

	//渲染LocalStorage(非IE7用户)
	function RenderStore(org) {
		UStore.clear();
		UStoreConst.home = org.deptList.length;
		for(var i = 0; i < UStoreConst.home; i++) {
			UStore.set("home_" + i.toString(), Dept2JSON(org.deptList[i]));
			if(org.deptList[i].deptName != "******") {
				for(var j = 0; j < org.deptList[i].childUsers.length; j++) {
					UStore.set("user_" + org.deptList[i].deptId + "_" + j.toString(), User2JSON(org.deptList[i].childUsers[j], org.deptList[i].deptId));
				}
			}
			for(var k = 0; k < org.deptList[i].childNodes.length; k++) {
				GetChildNode(org.deptList[i].childNodes[k], k, org.deptList[i].deptId);
			}
		}
	}

	//渲染HASH(IE7用户)
	function RenderHash(org) {
		UStoreConst.hash = {};
		UStoreConst.home = org.deptList.length;
		for(var i = 0; i < UStoreConst.home; i++) {
			UStoreConst.hash["home_" + i.toString()] = Dept2JSON(org.deptList[i]);
			if(org.deptList[i].deptName != "******") {
				for(var j = 0; j < org.deptList[i].childUsers.length; j++) {
					UStoreConst.hash["user_" + org.deptList[i].deptId + "_" + j.toString()] = User2JSON(org.deptList[i].childUsers[j], org.deptList[i].deptId);
				}
			}
			for(var k = 0; k < org.deptList[i].childNodes.length; k++) {
				GetChildNode(org.deptList[i].childNodes[k], k, org.deptList[i].deptId);
			}
		}
	}

	//获取用户、部门信息，通过KEY获取JSON对象格式
	function GetValue(key) {
		if(UStore.usable()) {
			return JSON.parse(UStore.get(key).toString());
		} else {
			return JSON.parse(UStoreConst.hash[key]);
		}
	}

	//修改用户、部门信息，通过KEY和VALUE设置
	function SetValue(key, value) {
		if(UStore.usable()) {
			UStore.set(key, JSON.stringify(value));
		} else {
			UStoreConst.hash[key] = JSON.stringify(value);
		}
	}

	//页面首次渲染(页面第一次展现的时候)
	function RenderPage() {
		var pageStr = "";
		for(var i = 0; i < UStoreConst.home; i++) {
			var home = GetValue("home_" + i.toString());
			pageStr += "<div id='home_" + i.toString() + "' class=\"shnode\">";
			pageStr += "<img src='assets/images/nright.png' class=\"arrow\" />";
			pageStr += "<span class=\"sele\">";
			if(_ucstyle === 0) {
				//多选，无论人员还是部门
				if(home.checked)
					pageStr += "<input checked=\"true\"   id='home_" + home.id + "' type=\"checkbox\" />";
				else
					pageStr += "<input  id='home_" + home.id + "' type=\"checkbox\" />";
			} else if(_ucstyle === 1 && _uctype === 1) {
				//单选，只针对部门选择
				if(home.checked)
					pageStr += "<input checked=\"true\"   id='home_" + home.id + "' name='usergroup' type=\"radio\" />";
				else
					pageStr += "<input  id='home_" + home.id + "' name='usergroup' type=\"radio\" />";
			}
			pageStr += ""
			if(_ucicon === 0 || _ucicon === 2)
				pageStr += "<img src=\"assets/images/org/home.png\"  />";
			pageStr += "</span>";
			pageStr += "<span class=\"tip\">";
			pageStr += home.name;
			pageStr += "</span>";
			pageStr += "<div class=\"scnode\">";
			pageStr += "<div class=\"sunode\">";
			pageStr += "<ul>";
			for(var j = 0; j < home.unum; j++) {
				var user = GetValue("user_" + home.id + "_" + j.toString());
				if(user.visiable === false || _uctype === 1) {
					continue;
				}
				pageStr += "<li>";
				if(_ucstyle === 0) {
					if(user.checked)
						pageStr += "<input  checked=\"true\"  id='user_" + user.id + "' type=\"checkbox\" />";
					else
						pageStr += "<input id='user_" + user.id + "' type=\"checkbox\" />";
				} else if(_ucstyle === 1) {
					if(user.checked)
						pageStr += "<input  checked=\"true\" id='user_" + user.id + "'  name='usergroup' type=\"radio\" />";
					else
						pageStr += "<input id='user_" + user.id + "'  name='usergroup' type=\"radio\" />";
				}
				if(_ucicon === 1 || _ucicon === 2)
					pageStr += "<img src=\"assets/images/org/user.png\"  />";
				pageStr += "<span style='color:" + user.color + "' uid='" + user.id + "' class=\"tip\">" + Common.CheckLength(user.name, 9) + "</span>";
				pageStr += "</li>";
			}
			pageStr += "</ul>";
			pageStr += "</div>";

			for(var k = 0; k < home.cnum; k++) {
				var dept = GetValue("dept_" + home.id + "_" + k.toString());
				pageStr += "<div id='" + "dept_" + home.id + "_" + k.toString() + "' class=\"sdnode\">";
				pageStr += "<img src='assets/images/nright.png' class=\"arrow\" />";
				pageStr += "<span class=\"sele\">";
				if(_ucstyle === 0) {
					//多选，无论人员还是部门
					if(dept.checked)
						pageStr += "<input checked=\"true\"   id='dept_" + dept.id + "'  type=\"checkbox\" />";
					else
						pageStr += "<input  id='dept_" + dept.id + "'  type=\"checkbox\" />";
				} else if(_ucstyle === 1 && _uctype === 1) {
					//单选，只针对部门选择
					if(dept.checked)
						pageStr += "<input checked=\"true\"   id='dept_" + dept.id + "' name='usergroup' type=\"radio\" />";
					else
						pageStr += "<input   id='dept_" + dept.id + "' name='usergroup' type=\"radio\" />";
				}
				if(_ucicon === 0 || _ucicon === 2)
					pageStr += "<img src=\"assets/images/org/block.png\"  />";
				pageStr += "</span>";
				pageStr += "<span class=\"tip\">";
				pageStr += dept.name;
				pageStr += "</span>";
				pageStr += "<div class=\"scnode\"></div>";
				pageStr += "</div>";
			}
			pageStr += "</div>";
			pageStr += "</div>";
		}
		$(".uc_content").html(pageStr);
	}

	//获取子部门
	function RenderCNode(deptid) {
		if($("#" + deptid).find(">.scnode").html() == "") {
			var dept = GetValue(deptid);
			var pageStr = "";
			pageStr += "<div class=\"sunode\">";
			pageStr += "<ul>";
			for(var j = 0; j < dept.unum; j++) {
				var user = GetValue("user_" + dept.id + "_" + j.toString());
				if(user.visiable === false || _uctype === 1) {
					continue;
				}
				pageStr += "<li>";
				if(_ucstyle === 0) {
					if(user.checked)
						pageStr += "<input  checked=\"true\"  id='user_" + user.id + "' type=\"checkbox\" />";
					else
						pageStr += "<input id='user_" + user.id + "' type=\"checkbox\" />";
				} else if(_ucstyle === 1) {
					if(user.checked)
						pageStr += "<input  checked=\"true\" id='user_" + user.id + "'  name='usergroup' type=\"radio\" />";
					else
						pageStr += "<input id='user_" + user.id + "'  name='usergroup' type=\"radio\" />";
				}
				if(_ucicon === 1 || _ucicon === 2)
					pageStr += "<img src=\"assets/images/org/user.png\"  />";
				pageStr += "<span style='color:" + user.color + "' uid='" + user.id + "' class=\"tip\">" + Common.CheckLength(user.name, 9) + "</span>";
				pageStr += "</li>";
			}
			pageStr += "</ul>";
			pageStr += "</div>";

			for(var k = 0; k < dept.cnum; k++) {
				var cdept = GetValue("dept_" + dept.id + "_" + k.toString());
				pageStr += "<div id='" + "dept_" + dept.id + "_" + k.toString() + "' class=\"sdnode\">";
				pageStr += "<img src='assets/images/nright.png' class=\"arrow\" />";
				pageStr += "<span class=\"sele\">";
				if(_ucstyle === 0) {
					//多选，无论人员还是部门
					if(cdept.checked)
						pageStr += "<input checked=\"true\"   id='dept_" + cdept.id + "'  type=\"checkbox\" />";
					else
						pageStr += "<input  id='dept_" + cdept.id + "'  type=\"checkbox\" />";
				} else if(_ucstyle === 1 && _uctype === 1) {
					//单选，只针对部门选择
					if(cdept.checked)
						pageStr += "<input checked=\"true\"   id='dept_" + cdept.id + "' name='usergroup' type=\"radio\" />";
					else
						pageStr += "<input   id='dept_" + cdept.id + "' name='usergroup' type=\"radio\" />";
				}
				if(_ucicon === 0 || _ucicon === 2)
					pageStr += "<img src=\"assets/images/org/block.png\"  />";
				pageStr += "</span>";
				pageStr += "<span class=\"tip\">";
				pageStr += cdept.name;
				pageStr += "</span>";
				pageStr += "<div class=\"scnode\"></div>";
				pageStr += "</div>";
			}
			$("#" + deptid).find(">.scnode").html(pageStr);
			$("#" + deptid).find(">.arrow").attr("src", "assets/images/ndown.png");

			if(_ucunfoldcascade === 1) {
				$("#" + deptid).find(">.scnode").find(">.sdnode").each(function() {
					RenderCNode(this.id);
				});
			}
		} else {
			if($("#" + deptid).find(">.scnode").is(":visible")) {
				$("#" + deptid).find(">.scnode").hide();
				$("#" + deptid).find(">.arrow").attr("src", "assets/images/nright.png");
			} else {
				$("#" + deptid).find(">.scnode").show();
				$("#" + deptid).find(">.arrow").attr("src", "assets/images/ndown.png");
			}
		}
		var dept = GetValue(deptid);
		if(dept.cnum == 0)
			return false;
		else
			return true;
	}

	//通过调整数据实现选择,页面后绑定
	function CheckCNodes(pdeptid, checked) {
		var dept = null;
		dept = GetValue(pdeptid);
		var user = null;
		var cdept = null;
		var uid = "";
		var did = "";
		for(var i = 0; i < dept.unum; i++) {
			uid = "user_" + dept.id + "_" + i.toString();
			user = GetValue(uid);
			user.checked = checked;
			SetValue(uid, user);
		}
		for(var j = 0; j < dept.cnum; j++) {
			did = "dept_" + dept.id + "_" + j.toString();
			cdept = GetValue(did);
			cdept.checked = checked;
			SetValue(did, cdept);
			CheckCNodes(did, checked);
		}
	}

	//节点选择
	function CheckNodes(cascade, pdeptid, checked) {
		var dept = null;
		var did = "";
		var cdept = null;
		dept = GetValue(pdeptid);
		dept.checked = checked;
		SetValue(pdeptid, dept);
		if(cascade) {
			var user = null;
			var uid = "";
			for(var i = 0; i < dept.unum; i++) {
				uid = "user_" + dept.id + "_" + i.toString();
				user = GetValue(uid);
				user.checked = checked;
				SetValue(uid, user);
			}
			for(var j = 0; j < dept.cnum; j++) {
				did = "dept_" + dept.id + "_" + j.toString();
				cdept = GetValue(did);
				cdept.checked = checked;
				SetValue(did, cdept);
				CheckCNodes(did, checked);
			}
		} else {
			var user = null;
			var uid = "";
			for(var i = 0; i < dept.unum; i++) {
				uid = "user_" + dept.id + "_" + i.toString();
				user = GetValue(uid);
				user.checked = checked;
				SetValue(uid, user);
			}
		}

	}

	//遍历所有节点，筛选用户,当参数为空或者不传递参数时则显示所有用户
	function FilterUsers(uidlist) {
		var user = null;
		if(uidlist === null || uidlist === "") {
			if(UStore.usable()) {
				for(var j = 0; j < UStore.getLength(); j++) {
					if(UStore.key(j).split("_")[0] !== "user")
						continue;
					user = JSON.parse(UStore.value(j));
					user.visiable = true;
					SetValue(UStore.key(j), user);
				}
			} else {
				for(name in UStoreConst.hash) {
					if( typeof UStoreConst.hash[name] === 'string') {
						if(name.split("_")[0] !== "user")
							continue;
						user = JSON.parse(UStoreConst.hash[name]);
						user.visiable = true;
						SetValue(name, user);
					}
				}
			}
			//重新渲染页面
			RenderPage();
			return;
		}

		//拆分用户ID形成数组
		var IDList = uidlist.split(",");
		if(UStore.usable()) {
			for(var j = 0; j < UStore.getLength(); j++) {
				if(UStore.key(j).split("_")[0] !== "user")
					continue;
				user = JSON.parse(UStore.value(j));
				var index = -1;
				for(var i = 0; i < IDList.length; i++) {
					if(IDList[i] === user.id) {
						index = i;
						break;
					}
				}
				if(index !== -1) {
					//剔除已经处理过的用户ID，提升效率
					IDList.splice(index, 1);
					user.visiable = true;
				} else {
					user.visiable = false;
				}
				SetValue(UStore.key(j), user);
			}
		} else {
			for(name in UStoreConst.hash) {
				if( typeof UStoreConst.hash[name] === 'string') {
					if(name.split("_")[0] !== "user")
						continue;
					user = JSON.parse(UStoreConst.hash[name]);
					var index = -1;
					for(var i = 0; i < IDList.length; i++) {
						if(IDList[i] === user.id) {
							index = i;
							break;
						}
					}
					if(index !== -1) {
						//剔除已经处理过的用户ID，提升效率
						IDList.splice(index, 1);
						user.visiable = true;
					} else {
						user.visiable = false;
					}
					SetValue(name, user);
				}
			}
		}

		//重新渲染页面
		RenderPage();
	}

	//渲染样式。。。。。。。。。。。。。。

	//展开折叠
	$(".arrow").live("click", function() {
		RenderCNode($(this).parent()[0].id);
	});
	//简单的页面选择，剩余部分在后台数据渲染
	$(".uc_content :checkbox").live("click", function() {
		if(this.id.split("_")[0] == "user") {
			var uid = $(this).parent().parent().parent().parent().parent().find(".sele :checkbox")[0].id;
			var tindex = $(this).parent().parent().find("li").length - $(this).parent().find("~li").length - 1;
			var user = null;
			suid = "user_" + uid.split("_")[1] + "_" + tindex.toString();
			user = GetValue(suid);
			if(this.checked) {
				user.checked = true;
			} else {
				user.checked = false;
			}
			SetValue(suid, user);
			return;
		}
		if(_uccascade == 1) {
			if(this.checked)
				$(this).parent().parent().find(".scnode").find(":checkbox").attr("checked", true);
			else
				$(this).parent().parent().find(".scnode").find(":checkbox").attr("checked", false);
			CheckNodes(true, $(this).parent().parent()[0].id, this.checked);

		} else {
			if(this.checked)
				$(this).parent().parent().find(">.scnode .sunode").find(":checkbox").attr("checked", true);
			else
				$(this).parent().parent().find(">.scnode .sunode").find(":checkbox").attr("checked", false);
			CheckNodes(false, $(this).parent().parent()[0].id, this.checked);
		}
	});
	//开放接口
	return {
		/*
		 获取选定用户，参数idType:0只包含ID，1只包含name,2包含ID和name
		 0：1001,1002,1003
		 1：赵,钱,孙
		 2：1001,1002,1003|赵,钱,孙
		 */
		GetSelUsers : function(idType) {
			var userList = "";
			var userNameList = "";
			var userId_Name = "";
			if(_ucstyle === 1) {
				$(":radio").each(function() {
					if(this.checked) {
						userList = this.id.split("_")[1];
						if(idType !== 0) {
							if(_uctype === 0)
								userNameList = $(this).parent().find(".tip").html();
							else
								userNameList = $(this).parent().parent().find(".tip").html();
						}
						return false;
					}
				});
				if(idType === 0)
					return userList;
				else if(idType === 1)
					return userNameList;
				else
					return userList + "|" + userNameList;
			}

			if(UStore.usable()) {
				for(var j = 0; j < UStore.getLength(); j++) {
					if(UStore.key(j).split("_")[0] !== "user" && _uctype === 0)
						continue;
					if(UStore.key(j).split("_")[0] !== "dept" && _uctype === 1)
						continue;
					user = JSON.parse(UStore.value(j));
					if(user.checked && user.visiable) {
						userList += user.id + ",";
						if(idType != 0) {
							userNameList += user.name + ",";
							userId_Name += user.id + "|" + user.name + ",";
						}
					}
				}
			} else {
				for(name in UStoreConst.hash) {
					if( typeof UStoreConst.hash[name] === 'string') {
						if(name.split("_")[0] !== "user" && _uctype === 0)
							continue;
						if(name.split("_")[0] !== "dept" && _uctype === 1)
							continue;
						user = JSON.parse(UStoreConst.hash[name]);
						if(user.checked && user.visiable) {
							userList += user.id + ",";
							if(idType != 0) {
								userNameList += user.name + ",";
								userId_Name += user.id + "|" + user.name + ",";
							}
						}
					}
				}
			}
			if(idType == 0)
				return userList.substring(0, userList.length - 1).Dist();
			else if(idType == 1)
				return userNameList.substring(0, userNameList.length - 1).Dist();
			else {
				userId_Name = userId_Name.substring(0, userId_Name.length - 1).Dist();
				var tempUserList = "";
				var id_name_array = userId_Name.split(",");
				for(var i = 0; i < id_name_array.length; i++) {
					if(i == id_name_array.length - 1)
						tempUserList += id_name_array[i].split("|")[0];
					else
						tempUserList += id_name_array[i].split("|")[0] + ",";
				}
				tempUserList += "|";
				for(var i = 0; i < id_name_array.length; i++) {
					if(i == id_name_array.length - 1)
						tempUserList += id_name_array[i].split("|")[1];
					else
						tempUserList += id_name_array[i].split("|")[1] + ",";
				}
				return tempUserList;
			}
		},
		SetSelUsers : function(uidlist) {
			//拆分用户ID形成数组
			var IDList = uidlist.split(",");
			if(UStore.usable()) {
				for(var j = 0; j < UStore.getLength(); j++) {
					if(UStore.key(j).split("_")[0] !== "user" && _uctype === 0)
						continue;
					if(UStore.key(j).split("_")[0] !== "dept" && _uctype === 1)
						continue;
					user = JSON.parse(UStore.value(j));
					var index = -1;
					for(var i = 0; i < IDList.length; i++) {
						if(IDList[i] === user.id) {
							index = i;
							break;
						}
					}
					if(index !== -1) {
						//剔除已经处理过的用户ID，提升效率
						IDList.splice(index, 1);
						user.checked = true;
					} else {
						user.checked = false;
					}
					SetValue(UStore.key(j), user);
				}
			} else {
				for(name in UStoreConst.hash) {
					if( typeof UStoreConst.hash[name] === 'string') {
						if(name.split("_")[0] !== "user" && _uctype === 0)
							continue;
						if(name.split("_")[0] !== "dept" && _uctype === 1)
							continue;
						user = JSON.parse(UStoreConst.hash[name]);
						var index = -1;
						for(var i = 0; i < IDList.length; i++) {
							if(IDList[i] === user.id) {
								index = i;
								break;
							}
						}
						if(index !== -1) {
							//剔除已经处理过的用户ID，提升效率
							IDList.splice(index, 1);
							user.checked = true;
						} else {
							user.checked = false;
						}
						SetValue(name, user);
					}
				}
			}
		},
		InitData : function(org) {
			//区分渲染模式
			if(!UStore.usable()) {
				RenderHash(org);
			} else {
				//这里可以增加部分控制，减少渲染频率，例如保存用户名和控件调用模式
				RenderStore(org);
			}
			org = null;
		},
		InitPage : function() {
			RenderPage();
			//单选时隐藏部分控件
			if(_ucstyle === 1) {
				$(".ucheader table tbody tr td").eq(0).hide();
				$(".ucheader table tbody tr td").eq(1).hide();
			}
		},
		SetCascade : function(value) {
			if(value)
				_uccascade = 1;
			else
				_uccascade = 0;
		},
		SetUnfoldCascade : function(value) {
			if(value)
				_ucunfoldcascade = 1;
			else
				_ucunfoldcascade = 0;
		},
		UserFilter : function() {
			FilterUsers(UStoreConst.filter.list);
		}
	}
}();
